package com.agileai.portal.controller.forum;

import java.util.List;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.TreeSelectHandler;
import com.agileai.hotweb.domain.TreeBuilder;
import com.agileai.hotweb.domain.TreeModel;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.portal.bizmoduler.forum.ForumSectionInfoTreeManage;
import com.agileai.util.ListUtil;

public class ForumSectionPickHandler
        extends TreeSelectHandler {
    public ForumSectionPickHandler() {
        super();
        this.serviceId = buildServiceId(ForumSectionInfoTreeManage.class);
        this.isMuilSelect = false;
    }

    public ViewRenderer prepareDisplay(DataParam param){
		this.setAttributes(param);
		TreeBuilder treeBuilder = provideTreeBuilder(param);
		TreeModel topTreeModel = treeBuilder.buildTreeModel();
		String pickTreeSyntax = null;
		if (isMuilSelect){
			pickTreeSyntax = getMuliPickTreeSyntax(topTreeModel, new StringBuffer());
		}else{
			pickTreeSyntax = getTreeSyntax(topTreeModel,new StringBuffer());	
		}
		this.setAttribute("pickTreeSyntax", pickTreeSyntax);
		this.setAttribute("fpmId", param.getString("FPM_ID"));
		return new LocalRenderer(getPage());
	}	
    
    protected TreeBuilder provideTreeBuilder(DataParam param) {
        List<DataRow> records = getService().findTreeRecords(param);
        TreeBuilder treeBuilder = new TreeBuilder(records, "FCI_ID",
                                                  "FCI_NAME", "FCI_PID");

        String excludeId = param.get("FCI_ID");
        treeBuilder.getExcludeIds().add(excludeId);

        return treeBuilder;
    }

	protected void buildTreeSyntax(StringBuffer treeSyntax,TreeModel treeModel){
		List<TreeModel> children = treeModel.getChildren();
		String parentId = treeModel.getId();
        for (int i=0;i < children.size();i++){
        	TreeModel child = children.get(i);
            String curNodeId = child.getId();
                String curNodeName = child.getName();
                if (!ListUtil.isNullOrEmpty(child.getChildren())){
                	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:setSelectTempValue('"+curNodeId+"','"+curNodeName+"')\");").append(newRow);
                }else{
                	treeSyntax.append("d.add('"+curNodeId+"','"+parentId+"','"+curNodeName+"',\"javascript:setSelectTempValue('"+curNodeId+"','"+curNodeName+"')\");").append(newRow);
                }
                this.buildTreeSyntax(treeSyntax,child);
        }
    }  
    
    protected ForumSectionInfoTreeManage getService() {
        return (ForumSectionInfoTreeManage) this.lookupService(this.getServiceId());
    }
}
